package com.vayne.main;

import com.vayne.bean.Person;

import java.beans.*;
import java.util.stream.Stream;

/**
 * Java Beans 理解 Demo 示例
 *
 * {@link java.beans.BeanInfo}
 * {@link PropertyDescriptor}
 *
 * @author xuerui.zhang
 * @since 2019/12/30 上午10:47
 */
public class BeanInfoDemo {

    public static void main(String[] args) throws IntrospectionException {
        // 第二个参数：Object.class 意思是 去掉这个属性
        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class, Object.class);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        Stream.of(propertyDescriptors).forEach(propertyDescriptor -> {
            System.out.println(propertyDescriptor);
            Class<?> propertyType = propertyDescriptor.getPropertyType();
            System.out.println(propertyType);
            String name = propertyDescriptor.getName();
            // age 字段添加 PropertyEditor
            // PropertyEditor 可以做类型转换，默认是 String -> String
            if ("age".equals(name)) {
                propertyDescriptor.setPropertyEditorClass(IntegerEditor.class);
            }
        });
    }

    static class IntegerEditor extends PropertyEditorSupport {

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Integer.valueOf(text));
        }
    }
}
